package com.spring.initialization;

import com.spring.annotation.ControllerScan;
import com.spring.context.ApplicationContext;
import com.spring.server.SpringServlet;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;

public class SpringBoot {

    public static void run(Class<?> primarySource, String... args){
        String packagePath = "";
        if (primarySource.isAnnotationPresent(ControllerScan.class)){
            ControllerScan annotation = primarySource.getAnnotation(ControllerScan.class);
            packagePath = annotation.value();
        }
        ApplicationContext.init(packagePath);
        TomcatStart();
    }

    /**
     * 初始化容器之后  启动Tomcat
     */
    private static void TomcatStart(){
        Tomcat tomcat = new Tomcat();

        Connector connector = new Connector();
        connector.setPort(8080);
        connector.setURIEncoding("UTF-8");
        tomcat.getService().addConnector(connector);

        // 创建 servletContext servlet上下文  可用于添加配置属性
        Context context = tomcat.addContext("", null);
//        context.addParameter("appType","01009DS");   测试添加配置属性
        tomcat.addServlet(context, "springServlet", new SpringServlet());
        context.addServletMappingDecoded("/","springServlet");

        try {
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
        tomcat.getServer().await();
    }
}
